package com.qkjia.day02;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test05_MyCache {
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    //缓存
    private Map<String, Object> cache = new HashMap<>();

    public Object getData(String key) {
        Object value;
        try {
            rwLock.readLock().lock();
            value = cache.get(key);
            rwLock.readLock().unlock();
            //主要是为了提升性能 不需要添加写锁
            if (value == null) {
                rwLock.writeLock().lock();
                //为了使用缓存
                if (value == null) {
                    value = "you are so intellegent";
                    cache.put(key, value);
                }
                rwLock.writeLock().unlock();
            }

            rwLock.readLock().lock();
        } finally {
            rwLock.readLock().unlock();
        }
        return value;
    }

    public static void main(String[] args) {
        Test05_MyCache myCache = new Test05_MyCache();
        Object data1 = myCache.getData("atguigu");
        Object data2 = myCache.getData("atguigu");
        System.out.println(data1);
        System.out.println(data2);
    }



}
